﻿using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IntelligentAgriculture.Domain.Impl
{
	/// <summary>
	/// 羔羊断奶仓储
	/// </summary>
	public class LambweaninginfoRepository: ILambweaninginfoRepository
	{
		/// <summary>
		/// 上下文
		/// </summary>
		private readonly AgricultureDbContext _context;
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="context"></param>

		public LambweaninginfoRepository(AgricultureDbContext context)
		{
			_context = context;
		}
		/// <summary>
		/// 获取羔羊断奶信息
		/// </summary>
		/// <returns></returns>
		public async Task<IQueryable<Lambweaninginfo>> GetLambweaninginfos()
		{
			return _context.Lambweaninginfos.Where(c => c.IsDel == false).AsQueryable();
		}
		/// <summary>
		/// 羊羔断奶删除
		/// </summary>
		/// <param name="ids"></param>
		/// <returns></returns>
		public async Task<int> DelLambweaninginfos(string loginUserName,params string[] eartag)
		{
			
			var result = _context.Lambweaninginfos.Where(c => eartag.Contains(c.EarTag));
			foreach(var item in result)
			{
				item.IsDel = true;
				item.UpdateName = loginUserName;
				item.UpdateTime = DateTime.Now;
			}
			var sheeps = _context.Sheepfilemodels.Where(c =>eartag.Contains(c.EarTag)).ToList();
			foreach(var item in sheeps)
			{
				var lambInfo = _context.Lambweaninginfos.FirstOrDefault(l => l.EarTag == item.EarTag);
				item.Growthstage = 1;
				item.ColumnId = lambInfo.CurrentField;
				item.BuildingId= lambInfo.CurrentBuilding;
			}
			return await _context.SaveChangesAsync();
		}
		/// <summary>
		/// 羔羊断奶添加
		/// </summary>
		/// <param name="lambweaninginfo"></param>
		/// <returns></returns>
		public async Task<int> AddLambweaninginfo(List<Lambweaninginfo> lambweaninginfo)
		{
			var result= _context.Lambweaninginfos.AddRangeAsync(lambweaninginfo);
			return await _context.SaveChangesAsync();
		}
		/// <summary>
		/// 反填羔羊断奶
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<Lambweaninginfo> DteilLambweaninginfo(string eartag)
		{
			var result=_context.Lambweaninginfos.Where(c => c.EarTag == eartag).FirstOrDefault();
			return result;
		}
		/// <summary>
		/// 批量修改羔羊断奶
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public async Task<int> UpdateListLambweaninginfo(List<Lambweaninginfo> entity)
		{
			_context.Lambweaninginfos.UpdateRange(entity);
			return await _context.SaveChangesAsync();
		}
		/// <summary>
		/// 修改羔羊断奶
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		public async Task<int> UpdateLambweaninginfo(Lambweaninginfo entity)
		{
			_context.Entry(entity).State = EntityState.Modified;
			return await _context.SaveChangesAsync();
		}
	}
}
